package com.mytaobao.main.cart;

import android.graphics.Paint;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baseproject.eventbus.EventBus;
import com.baseproject.imageload.ImageLoaderUtil;
import com.baseproject.util.LogUtils;
import com.baseproject.util.ToastUtils;
import com.mytaobao.R;
import com.mytaobao.main.cart.func.cart.ItemCommodity;
import com.mytaobao.main.cart.func.cart.SelectedChangeEvent;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hp on 2017/3/17.
 */

public class CartRecyclerViewSubAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener{

    List<ItemCommodity> mCommodities = new ArrayList<>();
    RecyclerView mRecyclerView;
    CartRecyclerViewAdapter mCartRecyclerViewAdapter;

    int mPosition;

    public CartRecyclerViewSubAdapter(CartRecyclerViewAdapter cartRecyclerViewAdapter) {
        mCartRecyclerViewAdapter = cartRecyclerViewAdapter;
    }

    public void setPosition(int position) {
         mPosition = position;
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        mRecyclerView = recyclerView;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder holder;
        if(viewType == 0) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_cart_subitem_title, parent, false);
            holder = new CartSubItemTitleViewHolder(itemView);
        } else {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_cart_subitem, parent, false);
            holder = new CartSubItemViewHolder(itemView);
        }
        return holder;
    }

    @Override
    public int getItemViewType(int position) {
        if(position == 0) {
            return 0;
        } else {
            return 1;
        }
    }

    private final class CartSubItemTitleViewHolder extends RecyclerView.ViewHolder {
        TextView tvShopName;
        CheckBox ivCheckGroup;
        TextView tvEdit;
        public CartSubItemTitleViewHolder(View itemView) {
            super(itemView);
            tvShopName = (TextView) itemView.findViewById(R.id.tvShopName);
            ivCheckGroup = (CheckBox) itemView.findViewById(R.id.ivCheckGroup);
            tvEdit = (TextView)itemView.findViewById(R.id.tvEdit);
        }
    }

    private final class CartSubItemViewHolder extends RecyclerView.ViewHolder {
        LinearLayout llCommodityInfo;
        RelativeLayout rlEditStatus;
        CheckBox ivCheck;
        ImageView ivImage;
        TextView tvIntro;
        TextView tvSpec;
        TextView tvSpecExtend;
        TextView tvPriceNow;
        TextView tvPriceBefore;
        TextView tvCountInCartEdit;
        TextView tvCountInCartNoEdit;
        ImageView ivReduce;
        ImageView ivAdd;
        TextView tvDel;
        FrameLayout flSubItem;

        public CartSubItemViewHolder(View itemView) {
            super(itemView);
            llCommodityInfo = (LinearLayout) itemView.findViewById(R.id.llCommodityInfo);
            rlEditStatus = (RelativeLayout) itemView.findViewById(R.id.rlEditStatus);
            ivCheck = (CheckBox) itemView.findViewById(R.id.ivCheck);
            ivImage = (ImageView) itemView.findViewById(R.id.ivImage);
            tvIntro = (TextView) itemView.findViewById(R.id.tvIntro);
            tvSpec = (TextView) itemView.findViewById(R.id.tvSpec);
            tvSpecExtend = (TextView) itemView.findViewById(R.id.tvSpecExtend);
            tvPriceNow = (TextView) itemView.findViewById(R.id.tvPriceNow);
            tvPriceBefore = (TextView) itemView.findViewById(R.id.tvPriceBefore);
            tvCountInCartEdit = (TextView) itemView.findViewById(R.id.tvCountInCartEdit);
            tvCountInCartNoEdit = (TextView) itemView.findViewById(R.id.tvCountInCartNoEdit);

            ivReduce = (ImageView) itemView.findViewById(R.id.ivReduce);
            ivAdd = (ImageView) itemView.findViewById(R.id.ivAdd);
            tvDel = (TextView) itemView.findViewById(R.id.tvDel);
            flSubItem = (FrameLayout) itemView.findViewById(R.id.flSubItem);
        }
    }

    String addString(String subString1, String subString2) {
        String string = "";
        if (!TextUtils.isEmpty(subString2)) {
            string += (subString1 + subString2);
        }
        return string;
    }

    private boolean ifAllChecked() {
        boolean allChecked = true;
        for (ItemCommodity itemCommodity : mCommodities) {
              if (!itemCommodity.isChildSelected()) {
                  allChecked = false;
                  break;
              }
        }
        return allChecked;
    }

    public void setAllChecked(boolean ifChecked) {
        CartSubItemTitleViewHolder cartSubItemTitleViewHolder = getCartSubItemTitleViewHolder();
        if(cartSubItemTitleViewHolder.ivCheckGroup.isChecked() != ifChecked) {
            cartSubItemTitleViewHolder.ivCheckGroup.setChecked(ifChecked);
        }
        for (int i = 0; i < mCommodities.size(); i++) {
            ItemCommodity itemCommodity = mCommodities.get(i);
            if (itemCommodity.isChildSelected() != ifChecked) {
                itemCommodity.setChildSelected(ifChecked);
            }
            View view = mRecyclerView.getChildAt(i + 1);
            CartSubItemViewHolder cartSubItemViewHolder = (CartSubItemViewHolder)mRecyclerView.getChildViewHolder(view);
            if(cartSubItemViewHolder.ivCheck.isChecked() != ifChecked) {
                cartSubItemViewHolder.ivCheck.setChecked(ifChecked);
            }
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        LogUtils.d("[onBindViewHolder] this = " + this + " positon = " + position);
        if(holder instanceof  CartSubItemViewHolder) {
            ItemCommodity commodity = mCommodities.get(position - 1);
            CartSubItemViewHolder subItemViewHolder = (CartSubItemViewHolder)holder;
            ImageLoaderUtil.getInstance().with(mRecyclerView.getContext())
                    .load(commodity.getImageUrl())
                    .into(subItemViewHolder.ivImage);
            subItemViewHolder.tvIntro.setText(commodity.getIntro());
            String specString = new String();
            specString += addString("颜色分类: ", commodity.getColorClassification());
            specString += addString("  尺码: ", commodity.getSize());
            specString += addString("  套餐类型: ", commodity.getTaoCanType());
            subItemViewHolder.tvSpec.setText(specString);
            subItemViewHolder.tvSpecExtend.setText(specString);
            subItemViewHolder.tvPriceNow.setText(String.valueOf(commodity.getPriceNow()));
            subItemViewHolder.tvPriceBefore.setText(String.valueOf(commodity.getPriceBefore()));
            subItemViewHolder.tvPriceBefore.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//数字被划掉效果
            if (!commodity.isInEditMode()) {
                subItemViewHolder.llCommodityInfo.setVisibility(View.VISIBLE);
                subItemViewHolder.rlEditStatus.setVisibility(View.GONE);
            } else {
                subItemViewHolder.llCommodityInfo.setVisibility(View.GONE);
                subItemViewHolder.rlEditStatus.setVisibility(View.VISIBLE);
            }
            subItemViewHolder.ivCheck.setChecked(commodity.isChildSelected());
            subItemViewHolder.ivCheck.setOnClickListener(this);

            subItemViewHolder.tvCountInCartEdit.setText(commodity.getCountInCart() + "");
            subItemViewHolder.tvCountInCartNoEdit.setText("X " + commodity.getCountInCart() + "");

            subItemViewHolder.ivReduce.setOnClickListener(this);
            subItemViewHolder.ivAdd.setOnClickListener(this);
            subItemViewHolder.tvDel.setOnClickListener(this);
            subItemViewHolder.flSubItem.setOnClickListener(this);
        } else if(holder instanceof CartSubItemTitleViewHolder){
            CartSubItemTitleViewHolder curHolder = ((CartSubItemTitleViewHolder)holder);
            if(mCommodities.size() > 0) {
                ItemCommodity commodity = mCommodities.get(0);
                curHolder.tvShopName.setText(commodity.getName());
                curHolder.ivCheckGroup.setChecked(ifAllChecked());
                curHolder.ivCheckGroup.setOnClickListener(this);
                setEditText(curHolder.tvEdit);
                curHolder.tvEdit.setOnClickListener(this);
            }
        }
    }

    @Override
    public void onClick(View v) {
        CartSubItemTitleViewHolder titleViewHolder = null;
        CartSubItemViewHolder viewHolder = null;
        RecyclerView.ViewHolder holder = mRecyclerView.findContainingViewHolder(v);
        int position = holder.getAdapterPosition();
        int dataPosition = (position - 1) >= 0 ? (position - 1) : 0;
        ItemCommodity itemCommodity = mCommodities.get(dataPosition);
        if (holder instanceof CartSubItemTitleViewHolder) {
            titleViewHolder = (CartSubItemTitleViewHolder)holder;
        } else if (holder instanceof  CartSubItemViewHolder) {
            viewHolder = (CartSubItemViewHolder)holder;
        }
        switch (v.getId()) {
            case R.id.ivReduce:
                if (!itemCommodity.reduceCountInCart()) {
                    ToastUtils.showSingleToast(R.string.cannot_reduce_commodity);
                } else {
                    if (itemCommodity.isChildSelected()) {
                        postSelectedChangeEvent();
                    }
                    viewHolder.tvCountInCartEdit.setText(itemCommodity.getCountInCart() + "");
                    viewHolder.tvCountInCartNoEdit.setText(itemCommodity.getCountInCart() + "");
                }
                break;
            case R.id.ivAdd:
                if (!itemCommodity.addCountInCart()) {
                    ToastUtils.showSingleToast(R.string.cannot_add_commodity);
                } else {
                    if (itemCommodity.isChildSelected()) {
                        postSelectedChangeEvent();
                    }
                    viewHolder.tvCountInCartEdit.setText(itemCommodity.getCountInCart() + "");
                    viewHolder.tvCountInCartNoEdit.setText(itemCommodity.getCountInCart() + "");
                }
                break;
            case R.id.tvDel:
                mCommodities.remove(itemCommodity);
                postSelectedChangeEvent();
                notifyItemRemoved(position);
                if(mCommodities.size() == 0) {
                    notifyItemRemoved(0);
                    mCartRecyclerViewAdapter.removeItem(mPosition);
                }
                break;
            case R.id.tvEdit:
                toogleEditStatus(titleViewHolder.tvEdit);
                notifyDataSetChanged();
                break;
            case R.id.ivCheckGroup:
                boolean isCheckGroupChecked = ((CheckBox)v).isChecked();
                setAllChecked(isCheckGroupChecked);
                postSelectedChangeEvent();
                break;
            case R.id.ivCheck:
                boolean isChecked = ((CheckBox)v).isChecked();
                itemCommodity.setChildSelected(isChecked);
                CartSubItemTitleViewHolder cartSubItemTitleViewHolder = getCartSubItemTitleViewHolder();
                if(ifAllChecked()) {
                    cartSubItemTitleViewHolder.ivCheckGroup.setChecked(true);
                } else {
                    cartSubItemTitleViewHolder.ivCheckGroup.setChecked(false);
                }
                postSelectedChangeEvent();
                break;
            case R.id.flSubItem:
               EventBus.getDefault().post(new String("startDetailActivity"));
        }
    }

    private CartSubItemTitleViewHolder getCartSubItemTitleViewHolder() {
        View view = mRecyclerView.getChildAt(0);
        return (CartSubItemTitleViewHolder)mRecyclerView.getChildViewHolder(view);
    }

    private CartSubItemViewHolder getCartSubItemViewHolder(int position) {
        View view = mRecyclerView.getChildAt(position);
        return (CartSubItemViewHolder)mRecyclerView.getChildViewHolder(view);
    }

    private void postSelectedChangeEvent() {
        EventBus.getDefault().post(new SelectedChangeEvent(0, 0));
    }

    private void setEditText(TextView tvEdit) {
        if (!mCommodities.get(0).isInEditMode()) {
            tvEdit.setText("编辑");
        } else {
            tvEdit.setText("完成");
        }
    }

    private void toogleEditStatus(TextView tvEdit){
        for (int i = 0; i < mCommodities.size(); i++) {
            ItemCommodity itemCommodity = mCommodities.get(i);
            itemCommodity.setInEditMode(!itemCommodity.isInEditMode());
        }
        if (!mCommodities.get(0).isInEditMode()) {
            tvEdit.setText("完成");
        } else {
            tvEdit.setText("编辑");
        }
    }

    @Override
    public int getItemCount() {
        int count  = mCommodities.size() > 0 ? (mCommodities.size() + 1) : 0;
        return count;
    }

    public void setCommodities(List<ItemCommodity> commodities) {
        if (commodities.size() > 0) {
            this.mCommodities = commodities;
        }
        notifyDataSetChanged();
    }
}
